<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | 首页控制器（App接口）
// +----------------------------------------------------------------------
// | Author: july <1499801239@qq.com>
// +----------------------------------------------------------------------
namespace app\index\controller;
use app\api\controller\User;
use http\Message;
use think\Controller;
use think\Db;
use think\Session;
use think\Request;
use changpay\ChangPay;
use app\index\controller\mopan\MoPan;
use app\common\controller\system\Docking;
use app\common\controller\chuanglan\ChuanglanSmsApi as CLApi;
use app\common\controller\order\Orderget;
use app\index\controller\System;
use app\api\controller\didi\Didi;
use app\api\controller\efficiency\Efficiency;
//use app\common\controller\system\Docking;

class App extends Base
{
    /**
    *支付方式(app)
    */
    public function payType(){
        $arr=[];
        $arr[0]['name']='微信支付';
        $arr[0]['Paytype']=1;
        $arr[1]['name']='支付宝支付';
        $arr[1]['Paytype']=2;

        $header =Request::instance()->header();
        $userId =$header['userid'];
        $ret = Db::table('xb_renzen_bank')->where('UserID',$userId)->find();
        if($ret){
            $arr[2]['name']=$ret['BankName'];
            $arr[2]['Paytype']=3;
            $arr[2]['BankNo'] =substr($ret['BankNo'],-4);
            return json_encode(array('status'=>1,'data'=>$arr,'msg'=>'数据获取成功'),JSON_UNESCAPED_UNICODE);
        }else{
            return json_encode(array('status'=>0,'data'=>null,'msg'=>'无订单'),JSON_UNESCAPED_UNICODE);
        }
    }



    /*
    * 首页(app) 未登录、未认证完整 显示最高；认证完成来最低 。
    */
    public function index(){
        $post = Request::instance()->header();
        $count =0;
        $arr =[];
        $userId = $post['userid'];
        $goodsLits = Db::table('xb_goods')->field('ID,SalePrice,jiekuandays')->where('IsShelves',1)->select();
        for($i=0;$i<count($goodsLits);$i++){
            $moneyArr[]=$goodsLits[$i]['SalePrice'];//额度列表
            $timeArr[]=$goodsLits[$i]['jiekuandays'];//借款周期
        }

        //最大额度
        $default = Db::table('xb_sys_basicinfo')->find();
        $arr['moneyArr']=$moneyArr;
        $arr['timeArr']=$timeArr;
        $arr['default']=$default['weimoney'];

        if($userId == -1){
            return json(['status'=>1,'data'=>$arr,'msg'=>'未登录数据获取成功']);
        }else{//登录用户

            $memRet = (new Member())->getUserInfo($userId);
            if(!$memRet) return json(['status'=>-2,'data'=>$arr,'msg'=>'非法用户']);

            $time =time();
            if($memRet['token'] !=$post['token']){
                return json(['status'=>-6,'data'=>null,'msg'=>'非法token']);
            }
            if($time-$post['token']>604800){
                return json(['status'=>-3,'data'=>$arr,'msg'=>'登录已过期']);
            }

            //查看认证项
            $authenArr = Db::table('xb_mem_info')->field('isID,isMobile,isSocial,isBank,refuseDay')->where('ID',$userId)->find();
            //查看必须认证项
            $mustAuthen = Db::table('xb_renzen_parameter')->where('IsMust',1)->select();
            if($authenArr){foreach($authenArr as $val){if($val==1){ $count ++;}}
            }else{
                return json(['status'=>0,'data'=>null,'msg'=>'暂时无法获取数据']);
            }
            $authenStatus = $count==count($mustAuthen)?true:false;

            //检测用户借款次数并获取对应可借金额
            $loanMoney = $this->getLoanMoney($userId);

            //借款项
            $applyData = Db::table('xb_loans_applylist')->where('UserID',$userId)->where('LoanStatus','in','0,1,2,5,6,7')->find();
            if($applyData){

                //订单逾期天数
                $YyFkTime= strtotime($applyData['YyFkTime']);
                $today= strtotime(date('Y-m-d 00:00:00'));
                $applyData['day']= $day = (int)ceil(($YyFkTime-$today)/86400);

                //确定是否续期开关 为前端 不得已 重复查询
                $goodAttr = Db::table('xb_loans_applylist a')->field('a.LoanStatus,a.ApplyMoney,a.ApplyDay,a.YyFkTime,a.OrderSn,b.Status,b.Statusyuqi')
                    ->join('xb_goods b','a.ProductID=b.ID','LEFT')
                    ->where('a.UserID',$userId)->where('a.LoanStatus','in','1,2,5,6,7')->find();
                if($day<0){
                    //逾期
                    if($goodAttr['Statusyuqi'] ==1){
                        $applyData['isShow']=1;
                    }else{
                        $applyData['isShow']=0;
                    }
                }else{
                    //未逾期
                    if($goodAttr['Status'] ==1){
                        $applyData['isShow']=1;
                    }else{
                        $applyData['isShow']=0;
                    }
                }
                //检测用户订单是否被拒 被拒判断被拒时间是否过于现在时间 过于让借款 否则不让借款
                if($applyData['LoanStatus']=='5'){

                    //计算用户被拒后的时间
                    $time = strtotime($applyData['FkTime']) + ($authenArr['refuseDay'] * 86400);
                    $applyData['ForbidDate'] =  date('Y-m-d H:i',$time);

                    if($time > time()){
                        $applyData['ForbidDate'] =  date('Y-m-d H:i',$time);
                    }else{
                        $arr['orderStatus']=-4;
                        $applyData = null;
                    }
                }
                $arr['orderStatus']=(string)$applyData['LoanStatus'];
            }else{
                $arr['orderStatus']=-4;
                $applyData=null;
            }

            //获取订单应还金额
            if($applyData){
                $applyData['ApplyMoney'] = (new Order())->getOrderShould($applyData);
            }
//			p($loanMoney);die;
            if($authenStatus){
                $arr['moneyArr']=array_column($loanMoney,'SalePrice');
                $arr['timeArr']=array_column($loanMoney,'jiekuandays');
			
                $arr['default']=max(array_column($loanMoney,'SalePrice'));
                $arr['authenStatus']=$authenStatus;
                $arr['applyData']=$applyData?$applyData:null;
            }else{
                $arr['authenStatus']=false;
                $arr['orderStatus']=-4;
                $arr['applyData']=null;
            }
            return json(['status'=>1,'data'=>$arr,'msg'=>'数据获取成功']);
        }
    }

    /**
     * 检测用户借款次数并获取对应可借款金额数据
     * @param int $usertID 用户ID
     * @return array
     */
    private function getLoanMoney($userID)
    {
        //获取用户陈功借款次数
        $LoanNum = db('loans_applylist')->where(['UserID' => $userID,'LoanStatus' => 3])->count('ID');
        if($LoanNum == 0){//如果是0取默认额度 否则更具提额规则查找已上线的订单号
            $money[0] = db('goods')->where(['defont' => 1, 'IsShelves' => 1])->find();
        }else{
            $where['t.num'] = ['<=',$LoanNum];
            $where['a.IsShelves'] = 1; //是否上架: 0 未上架 1 已上架
            $money = db('goods')->alias('a')
                ->join('xb_sys_tier t','a.ID = t.money','left')
                ->group('a.ID')
                ->where($where)
                ->select();
        }
        return $money;
    }

    //认证页（APP）
    public function authen(){
    	$header =Request::instance()->header();
        $post = $this->request->param(true);
        $result = Db::table('xb_mem_info')->field('isID,isMobile,isSocial,isBank')->where('ID',$header['userid'])->find();
        $data = Db::table('xb_renzen_parameter')->field('Name,Codes')->where('isShow',1)->select();
        $isAuth = model('System')->getSystemInfo();

        if($result && $data){
		foreach ($data as $k => $v) {
			if($v['Codes']=='card'){
                $data[$k]['isAuthen']=$result['isID'];
                $data[$k]['Codes']='isID';

			}if($v['Codes']=='mobile'){
				$data[$k]['isAuthen']=$result['isMobile'];
				$data[$k]['Codes']='isMobile';
				$data[$k]['Type'] = $isAuth['mobile_operator']??1;//1 调用魔蝎认证 2调用新颜认证接口 api.php/xinyan/xinyan/getOperator
			}
			if($v['Codes']=='social'){
				$data[$k]['isAuthen']=$result['isSocial'];
				$data[$k]['Codes']='isSocial';
				
			}
			if($v['Codes']=='bank'){
				$data[$k]['isAuthen']=$result['isBank'];
				$data[$k]['Codes']='isBank';
			}
		}
          
			show_success_api($data);
        }else{
        	show_error_api('数据异常');
            
        }
    }

    /**
	 * 订单确认页面
	 * 生成预订单
	 * 存入xb_loans_cart表
	 * 每个用户只能存在一条预订单  如果存在就覆盖 如果没有就新增
	 */
    public function apply(){
        $header = Request::instance()->header();//
        $applyData = $this->request->param(true);//接收数据
        $userId=$header['userid'];
        $arr =[];
        $user =Db::table('xb_mem_info')->where('ID',$userId)->find();
		$count =0;//该用户认证的个数
        $result = Db::table('xb_mem_info')->field('isID,isMobile,isSocial,isBank')->where('ID',$userId)->find();
        if($result){
            foreach($result as $val){
                if($val==1){
                    $count ++;
                }
            }
        }
        $must = Db::table('xb_renzen_parameter')->where('IsMust',1)->select();//获取必备认证的个数
        $must =count($must);
        if($count<$must){
			show_error_api($message='尚未认证完整');
        }   
//		判断用户年龄是是否服务系统配置里面的年龄
//		获取用户年龄
        $Yddatas= Db::table('xb_renzen_cards')->where('UserID',$userId)->value('Yddatas');
		$Yddatas=json_decode($Yddatas,1);
		$age=$Yddatas['data']['age'];
	    $Orderget=new Orderget();
	    $basicinfo=$Orderget->get_basicinfo();//获取系统高配置数据
	    if($age>$basicinfo['MaxAges']){
			show_error_api($message='年龄超过不符合借款规定');
	    }
		
        $result = Db::table('xb_loans_applylist')->where('UserID',$userId)->where('LoanStatus','in',[0,1,2,5,6,7])->find();
        if($result){
        	if($result['LoanStatus']=='5'){
//      		已经拒绝的订单   这里以后看老板要求操作
        	}else{
        	  show_error_api($message='有订单尚未完成');
        	}
        }
        $productRet = Db::table('xb_goods')->field('ID,SalePrice,jiekuandays,daoqiyinghua,daozhang,GuanliCost,zhanqifei,yuqulv,nianhualilv')->where('SalePrice',$applyData['ApplyMoney'])->find();
        $productRet['TrueName']=$user['TrueName'];
        $productRet['YyFkTime']=date('Y-m-d',strtotime('+'.($applyData['ApplyDay']-1).'days'));
        $productRet['CreateTime']=date('Y-m-d H:i:s');
        $productRet['ProductID']=$productRet['ID'];
        $productRet['UserID']=$userId;
		$user_type = Db::table('xb_loans_applylist')->where('UserID',$userId)->where('LoanStatus','in',[3])->find();
//		客户类型
		if($user_type){
			$productRet['user_type']='2';
			$productRet['app_type']='2';
			
		}else{
			$productRet['user_type']='1';
			$productRet['app_type']='1';
		}
//		订单类型
		
        $arr['productRet'] =$productRet;
		$re_data=Db::table('xb_loans_cart')->where(['UserID'=>$userId])->find();
		if($re_data){
			 unset($productRet['ID']);
			$re=Db::table('xb_loans_cart')->where(['UserID'=>$userId])->update($productRet);
			if($re){
				$arr['cartId']=$re_data['ID'];
			}
		}else{
			 unset($productRet['ID']);
//			 p($productRet);die;
			 
			 $arr['cartId'] = Db::table('xb_loans_cart')->insertGetId($productRet);
		}
        if($arr['cartId']){
			show_success_api($arr);
        }else{
            show_error_api($message='预订单生成失败');
        }
    }


//风控选择判断   1 滴滴 2 磨盘
public function fengkong_xuanzai($sys_basicinfo,$userId,$data,$post){
			    if($sys_basicinfo['fengkong']=='1'){//调取滴滴风控系统返回的是分数
				$Didi=new Didi();
				$realScore = $Didi->didi($userId,$data['ApplyTime']);//唐小文  魔蝎  新颜 通用  订单申请时间
//		        $realScore=$this->fengkong_jiuwei($userId);//只适用于魔蝎
		        $real = json_decode($realScore,1);
//				p($real);die;
		        if($real['return_code']!=0){
//		                       把错误的风控结果存入数据库
                $data['ShadminID']= '119';//审核员
		        $data['LoanStatus']= '5';
				$data['jishen']=$real['return_info'];
				Db::table('xb_loans_applylist')->where(['UserID'=> $data['UserID'],'OrderSn'=>$data['OrderSn']])->update($data);	
//	      	    show_error_api($message=$real['return_info']);
					show_error_api($message='滴滴风控系统调用失败');die;
		        }else{
		           return $realScore =$real['score']; //  风控分
		        }
//	            return $realScore='300';//测试用的 分控分
	            }else if($sys_basicinfo['fengkong']=='2'){//调用磨盘风控系统 返回的是结果
	//          获取客户类型
				$user_type= Db::table('xb_loans_applylist')->where(['LoanStatus'=>'3','UserID'=>$userId])->find();
				if($user_type){
					$user_type=='2';//老客
				}else{
					$user_type=='1';//新客
				}
	        	$mopan=new MoPan();
//				$data['OrderSn']='12345';
				$realScore = $mopan->getMoPanIntegral($userId,$data['OrderSn'],$post['MobileType'],$user_type,$data['ApplyMoney'],$data['ApplyTime']);
				$realScore=json_decode($realScore,1);
				if($realScore['code']=='000000'){
					return $realScore['code'];
				}else{
					Db::table('xb_loans_applylist')->where(['UserID'=> $data['UserID'],'OrderSn'=>$data['OrderSn']])->update(['jishen'=>$realScore['code']]);	
					show_error_api($message='磨盘风控系统调用失败');
					show_error_api($realScore['msg']);
                   
				}
	        }
}

//      风控开关  1开启 2关闭
//      开启  新客户老客户都调用风控  
//      关闭  新客户调用  老客户走根据静默时间和借款次数判断是否调用
public function fengkong($sys_basicinfo,$userId,$data,$post){
	  if($sys_basicinfo['fengkong_kaiguan']=='1'){//全部调用风控
	        return $this->fengkong_xuanzai($sys_basicinfo,$userId,$data,$post);
		   }else if($sys_basicinfo['fengkong_kaiguan']=='2'){//新客户调用  老客户走根据静默时间和借款次数判断是否调用
			$kehuleixing= Db::table('xb_loans_applylist')->where(['LoanStatus'=>'3','UserID'=>$userId])->order('ID desc')->find();
//			P($kehuleixing);DIE;
			if($kehuleixing){//老客户
//				查询静默时间  
				$SjFkTime= strtotime($kehuleixing['SjFkTime']);
				$days=$sys_basicinfo['fengkong_time'];
				$time=86400*$days;
				$SjFkTime=$SjFkTime+$time;
//				借款次数
                $count= Db::table('xb_loans_applylist')->where(['LoanStatus'=>'2','UserID'=>$userId])->count();
				if($SjFkTime>time() && $count<$sys_basicinfo['fengkong_nums']){
//					echo 12;die;
					return '免审核';
				}else{
//					echo 36;die;
					return $this->fengkong_xuanzai($sys_basicinfo,$userId,$data,$post);
				}
			}else{
				 return $this->fengkong_xuanzai($sys_basicinfo,$userId,$data,$post);
			}
		}
}

//效率花呗 用户申请贷款
			public function xlhb_jiekuan($userId,$orderId){
		        $TgadminID1=Db::table('xb_mem_info')->where('ID',$userId)->value('TgadminID');//用户推广ID
	            $TgadminID2=Db::table('xb_tg_admin')->where('Name','效率花呗')->value('ID');//效率花呗ID
				if($TgadminID1==$TgadminID2){
	               $Efficiency = new Efficiency();
//					p($orderId);
				   $re=$Efficiency->totle($orderId,1);
				   $re=json_encode($re,JSON_UNESCAPED_UNICODE);
				   $songsong=Db::table('xb_loans_applylist')->where('ID',$orderId)->update(['xlhb_jiekuan'=>$re]);
				}
			}

//效率花呗 用户订单审批
			public function xlhb_shenpi($userId,$orderId,$msg=''){
		        $TgadminID1=Db::table('xb_mem_info')->where('ID',$userId)->value('TgadminID');//用户推广ID
	            $TgadminID2=Db::table('xb_tg_admin')->where('Name','效率花呗')->value('ID');//效率花呗ID
				if($TgadminID1==$TgadminID2){
	               $Efficiency = new Efficiency();
				   $re=$Efficiency->totle($orderId,2);
				   $re=json_encode($re,JSON_UNESCAPED_UNICODE);
				   $songsong=Db::table('xb_loans_applylist')->where('ID',$orderId)->update(['xlhb_shenpi'=>$re,'fail_reason'=>$msg]);
				}
			}
			
     /**
	 * 确认借款操作
	 * 生成订单表
	 * 存入xb_loans_applylist表
	 * 查询分控    
	 * 调用自动放款
	 */
    function applyIndeed()
    {
    	//写入对接产品记录表
        $header =Request::instance()->header();
        $userId=$header['userid'];
	    $post = $this->request->param(true);
        $sys_basicinfo=Db::table('xb_sys_basicinfo')->find();//订单状态:1开启 2关闭
        $zijiren=[9999999999,8888888888888888,1];
         if(in_array($userId, $zijiren)){
//      	自己人  测试用
        }else{
//      	判断系统是否停止受理订单
	        if($sys_basicinfo['order']=='2'){
				show_error_api($message='系统已经停止受理订单');
	        }
	        //检测用户是否有借款中的订单
	        $isOrderWhere['LoanStatus'] = ['in','0,1,2,6,7'];
	        $isOrderWhere['UserID'] = $userId;
	        $isOrder = db('loans_applylist')->where($isOrderWhere)->find();
	        if($isOrder){
	            show_error_api('你有进行中的订单，暂时不能借款');
	        }
	        //检测上笔但是是否被拒，被拒返回剩余可再次借款时间提醒
	        $isOrder = db('loans_applylist')->where(['UserID' => $userId,'LoanStatus' => 5])->order('id','desc')->find();
	        if ($isOrder) {
                $days = (int) db('mem_info')->where(['ID' => $userId])->value('refuseDay');
                $refuseTime = date('Y-m-d H:i:s', strtotime($isOrder['ShTime']) + ($days * 86400));
                if (strtotime($refuseTime) > time()) {
                    $time = '你已有一笔被拒绝订单，请于'.date('Y-m-d H:i:s', strtotime($isOrder['ShTime']) + ($days * 86400)).'后再次申请';
                    show_error_api($time);
                }
            }
        }
//		写入消费统计
		if($sys_basicinfo['fengkong']=='1'){
		(new Docking())->addDocking(5,2,'didi','借款调用滴滴风控');
		}
		if($sys_basicinfo['fengkong']=='2'){	
    	(new Docking())->addDocking(4,2,'mopan','借款调用磨盘风控');
		}
        $applyData = Db::table('xb_loans_cart')->where('ID',$post['cartId'])->find();
        $data['UserID'] =$userId;//用户ID
        $data['OrderSn'] =date('Ymd') . rand(1, 9) . date('His') . rand(111, 999); //订单号
        $data['ApplyTime']=date('Y-m-d H:i:s');//申请时间
        $data['ApplyMoney']=(int)$applyData['SalePrice'];//申请金额
        $data['ApplyDay'] =(int)$applyData['jiekuandays'];//借款期限
        $data['YyFkTime']=$applyData['YyFkTime'];//预约还款时间
        $data['AdoptMoney']=$applyData['daozhang'];//到账金额
        $data['daoqiMoney']=$applyData['daoqiyinghua'];//到期应还
        $data['Interest']=$applyData['GuanliCost'];//服务费
        $data['ProductID']=$applyData['ProductID'];//产品ID
        $data['zhanqifei']=$applyData['zhanqifei'];//展期费用
        $data['yuqililv']=$applyData['yuqulv'];//逾期利率
        $data['nianhualilv']=$applyData['nianhualilv'];//年化利率
        $data['user_type']=$applyData['user_type'];//客户类型 1新客 2老客
        $data['app_type']=$applyData['app_type'];//订单类型 1新客 2老客
        $data['LoanStatus']= '0';//待审核
// 		p($data);die;
        $orderId = Db::table('xb_loans_applylist')->insertGetId($data);
//		p($orderId);die;
		if($orderId){
//			更改用户状态为审核通过
		    Db::table('xb_mem_info')->where('ID',$header['userid'])->update(['Status'=>'2']);
		    echo  json_encode(array('status'=>1,'data'=>null,'msg'=>'申请成功'),JSON_UNESCAPED_UNICODE);
            $size = ob_get_length();
            header("Content-Length: $size");
            header('Connection: close');
            header("HTTP/1.1 200 OK");
            header("Content-Type: application/json;charset=utf-8");
            ob_end_flush();
            if(ob_get_length())
                ob_flush();
            flush();
            if (function_exists("fastcgi_finish_request")) { // yii或yaf默认不会立即输出，加上此句即可（前提是用的fpm）
                fastcgi_finish_request(); // 响应完成, 立即返回到前端,关闭连接
            }
            ignore_user_abort(true);//在关闭连接后，继续运行php脚本
            set_time_limit(0); //no time limit，不设置超时时间（根据实际情况使用）
            //继续运行的代码
            sleep(5);
//			调用效率花呗
			$this->xlhb_jiekuan($userId,$orderId);
//			echo 22;die;
			$realScore=$this->fengkong($sys_basicinfo,$userId,$data,$post);//走风控流程
//			p($realScore);die;
			
//			$realScore='1';
			if($realScore==='免审核'){//如果等于免审核说明没有调用风控   就去找该用户上一次订单的风控结果
//			echo 3;die;
			     $songsong=Db::table('xb_loans_applylist')->where('UserID',$header['userid'])->order('ID DESC')->find();
			     $data['jishen']=$songsong['jishen'];
				 $data['ShadminID']= '119';//机器审核客服
	             $data['LoanStatus']= '1';
			}else if($realScore==='000000'){//此时调用了 磨盘 进入等待人工审核  等待磨盘回调更改订单状态
//			echo 4;die;
				 $data['LoanStatus']= '0';// 
				 $data['jishen']=$realScore;//机器审核结果//此时 调用了 滴滴风控 根据分数 判断订单状态
			}else{
//				echo 5;die;
				 $data['jishen']=$realScore;//机器审核结果//此时 调用了 滴滴风控 根据分数 判断订单状态
		        //获取此用户渠道
		        $TgadminID =Db::table('xb_mem_info')->where('ID',$header['userid'])->value('TgadminID');
		        if(!$TgadminID){
		        	show_error_api($message='查询用户渠道异常');
		        }
		        $fenkongfen =Db::table('xb_tg_admin')->where('ID',$TgadminID)->find(); //渠道分
		        $jishenfen=$fenkongfen['jishenfen'];
		        $rengongfen=$fenkongfen['rengongfen'];
		        if($jishenfen==0 && $rengongfen==0){
		            $xitongfengkong = Db::table('xb_sys_basicinfo')->find();
		            if(empty($xitongfengkong['rengongfen'])){
		            	show_error_api($message='系统分设置异常');
		            }else{
			            $jishenfen=$xitongfengkong['jishenfen'];//机审核分
			            $rengongfen=$xitongfengkong['rengongfen'];//人工分
		            }
		        }
//				p($realScore);
//				p($jishenfen);
//				p($rengongfen);
////				die;
		//      如果风控分小于人工分  直接拒绝
		        if($realScore<$rengongfen){
		            $data['ShadminID']= '119';//审核员
		            $data['LoanStatus']= '5';
					
		        }
		//        如果风控分大于机审分 直接通过 自动放款
		        if($realScore>=$jishenfen){
		        	$data['ShadminID']= '119';//审核员
		        	$data['FkadminID']= '125';//放款专员
		            $data['LoanStatus']= '1';
		        }
		//      如果风控大于等于人工  小于等于机审分  进入待审核状态
		        if($realScore>=$rengongfen && $realScore<$jishenfen){
		            $data['LoanStatus']= '7';
					$DShadminID=Db::table('xb_sys_administrator')->where('RoleID','55')->column('ID'); //渠道分
//					p($DShadminID);
					$num=count($DShadminID)-1;
		            $DShadminID = $DShadminID[rand(0,$num)];
//					p($DShadminID);die;
					$data['ShadminID']= $DShadminID;
		        }
			}
//p($data);die;
//			更新走完风控得订单
            $data['ShTime']=date('Y-m-d H:i:s');//审核时间
            $orderIup = Db::table('xb_loans_applylist')->where(['ID'=> $orderId])->update($data);
//			效率花呗直接拒绝
			if($data['LoanStatus']=='5'){
			$this->xlhb_shenpi($userId,$orderId,'直接拒绝');
				
			}
		    if($data['LoanStatus']=='1'){//判断是否进入打款流程
		        if($sys_basicinfo['zdfk']=='1'){//判断系统配置是否允许自动打款
					$Orderget=new Orderget();
				    $Payceshi=$Orderget->get_Payceshi();//获取支付环境
			        if($Payceshi=='1'){//获取支付环境
			        	$do['TransAmt'] = (int)$data['AdoptMoney'];
			         
			        }else{
			            $do['TransAmt'] = '0.02';
			        }
			        $do['PartnerId'] =$Orderget->get_changpay();//获取商户号
			        $bankDatas=Db::table('xb_renzen_bank')->field('BankNo,BankName')->where('UserID',$userId)->find();
			        if(!$bankDatas){
			        	show_error_api($message='获取用户银行卡信息异常');
			        }  
					$user =Db::table('xb_mem_info')->where('ID',$userId)->find();
			        $do['AcctNo'] = $bankDatas['BankNo'];
			        $do['AcctName'] = $user['TrueName'];
			        $do['BankCommonName'] = $bankDatas['BankName'];
		        //支付参数结束
		            $changpay= new \changpay\ChangPay;
		            $datas = $changpay->payment($do);//调用畅捷代付款
//					p($datas);die;
		            if($datas['AcceptStatus']=='S'){
		                $data_update['OutTradeNo']=$datas['OutTradeNo'];//支付订单号
		                $data_update['LoanStatus']='6';//订单状态
		                $data_update['pay'] = 4;//支付方式
		                Db::table('xb_loans_applylist')->where(['ID' => $orderId])->update($data_update);
						echo '自动放款成功';die;
		
		            }else{
						if(!empty($datas['RetMsg'])){
		            	 $data_update['fail_reason']=$datas['RetMsg'];//支付返回错误提示
						}else{
		            	 $data_update['fail_reason']=$datas['Memo'];//支付返回错误提示
						}
		            	 Db::table('xb_loans_applylist')->where(['ID' => $orderId])->update($data_update);
						 echo '自动放款失败';die;
		            }
	            }else{
		        	$data_update['fail_reason']='自动放款已经关闭';//支付返回错误提示
			        Db::table('xb_loans_applylist')->where(['ID' => $orderId])->update($data_update);
		        	echo '自动放款已经关闭';die;
	            }
	        }else{
	        	echo '自动拒绝/或者等待人工审核';die;
	        }
		}else{
			show_error_api($message='申请订单失败 ,请稍后重试');
		}
       
    }
    /*
    *借款记录 同一时间内，一个用户只有一个订单在 审核中 打款中 放款中(app)
    */
    public function applyRecord(){
        $header = Request::instance()->header();
        $userId = $header['userid'];
        $arr=[];
        $result = Db::table('xb_loans_applylist')->where('UserID',$userId)->where('LoanStatus','in','0,1,2,6,7')->find();//进行中的
        
        if($result['LoanStatus']=='0'){
        	$result['LoanStatus']='7';
        }
        
        if($result){
            $orderObj = new Order();
            $arr['applying'] = [
                'ID'          => $result['ID'],
                'OrderSn'     => $result['OrderSn'],           //订单编号
                'ApplyTime'   => $result['ApplyTime'],         //订单申请时间
                'ApplyMoney'  => $result['ApplyMoney'],        //借款金额
                'ApplyDay'    => $result['ApplyDay'],          //借款周期
                'daoqiMoney'  => $result['daoqiMoney'],        //到期应还
                'LoanStatus'  => $result['LoanStatus'],        //订单状态
                'fakuan'      => $orderObj->getOrderPenalty($result), //订单罚息
                'datas'       => $orderObj->isOrderOverdue($result),  //逾期天数
                'totle'       => $orderObj->getOrderShould($result),  //应还金额
                'YyFkTime'    => date('Y-m-d',strtotime($result['YyFkTime'])), //预约还款日
            ];
        }else{
            $arr['applying']=null;
        }

//p($arr);die;

//		已完成订单
        $results = Db::table('xb_loans_applylist')->field('ID,OrderSn,ApplyTime,ApplyMoney,ApplyDay,LoanStatus,YyFkTime,SjFkTime')->where('UserID',$userId)->where('LoanStatus','in','3,4,5')->select();//已完成的
        if($results){
        	foreach ($results as $key => $val) {
                if($val['LoanStatus']=='3'){
                    $hkRes = Db::table('xb_loans_hklist')->where('ApplyID',$val['ID'])->where('UserID',$userId)->select();
                    if($hkRes){
                    	$TotalMoney=0;
						foreach ($hkRes as $k => $v) {
							$TotalMoney=$TotalMoney+$v['TotalMoney'];
						}
						 $results[$key]['SjMoney']=$TotalMoney;
                    }else{
                        show_success_api($message='还款异常');
                    }
                }else{
                	 $results[$key]['SjMoney']='0';
                }
            }
            $arr['applied']=$results; 
        }else{
            $arr['applied']=[];
        }
		show_success_api($arr);
    }
   /*
    *借款详情
    */
    public function applyDetail(){
        
        return json_encode(array('status'=>1,'data'=>null,'msg'=>'验证码发送成功'),JSON_UNESCAPED_UNICODE);
    }
   /*
    *订单详情(app)
    */
    public function orderDetail(){
        $header = Request::instance()->header();
        $post =$this->request->param(true);
        $time=time();
        $applyData = $this->request->param(true);
//        if(!isset($header['userid']))  return json_encode(array('status'=>-2,'data'=>null,'msg'=>'非法用户'),JSON_UNESCAPED_UNICODE);
//        if(!isset($header['token']))  return json_encode(array('status'=>-2,'data'=>null,'msg'=>'非法用户'),JSON_UNESCAPED_UNICODE);
        if(!isset($post['ID']))  return json_encode(array('status'=>0,'data'=>null,'msg'=>'不合法的订单ID'),JSON_UNESCAPED_UNICODE);
        $ret = Db::table('xb_mem_info')->where('token',$header['token'])->find();
        $user =Db::table('xb_mem_info')->where('ID',$header['userid'])->find();
        if(!$ret && !$user){
            return json_encode(array('status'=>-2,'data'=>null,'msg'=>'非法用户'),JSON_UNESCAPED_UNICODE);
        }
        if($time-$header['token']>604800){
            return json_encode(array('status'=>-3,'data'=>null,'msg'=>'登录已过期'),JSON_UNESCAPED_UNICODE);
        }
        $ret = Db::table('xb_loans_applylist')->field('ID,OrderSn,ApplyTime,ApplyMoney,ApplyDay,LoanStatus,YyFkTime,yuqililv')->where('ID',$post['ID'])->find();
        if($ret){
            $YyFkTime = strtotime($ret['YyFkTime']);
            $today = strtotime(date('Y-m-d 00:00:00'));
            $day = (int)ceil(($YyFkTime-$today)/86400);
            $ret['shouldPay']=$ret['ApplyMoney'];
            $hkRes = Db::table('xb_loans_hklist')->where('ApplyID',$post['ID'])->where('UserID',$header['userid'])->find();
            if($day<0){//逾期
                if($ret['LoanStatus'] =='3')
                {//已完成
                    if($hkRes){
                        $ret['Hktime'] =$hkRes['HkTime'];
                        $ret['sjPay'] =$hkRes['TotalMoney'];
                        $tDay = strtotime($ret['Hktime']);
                        $day=(int)ceil(($YyFkTime-$tDay)/86400);
                    }else{
                        return json_encode(array('status'=>0,'data'=>null,'msg'=>'订单异常'),JSON_UNESCAPED_UNICODE);
                    }
                    $ret['Yqdays']=abs($day);
                    $ret['YqMoney']=$ret['ApplyMoney']*$ret['Yqdays']*$ret['yuqililv'];
                }else{//取消或者拒绝
                    $ret['Yqdays']=0;
                    $ret['YqMoney']=0;
                    $ret['Hktime'] =$ret['ApplyTime'];
                    $ret['sjPay'] =0;                   
                }
            }else{//没有逾期
                $ret['Yqdays']=0;
                $ret['YqMoney']=0;
                $ret['Hktime'] =$hkRes['HkTime'];
                $ret['sjPay'] =$hkRes['TotalMoney'];
            }
            return json_encode(array('status'=>1,'data'=>$ret,'msg'=>'成功'),JSON_UNESCAPED_UNICODE);
        }else{
            return json_encode(array('status'=>0,'data'=>null,'msg'=>'失败'),JSON_UNESCAPED_UNICODE);
        }
    }

    /**
    *账单续期(app)
    */
    public function orderRenewal(){
        $post = $this->request->param(true);
        $arr =[];
        $time = time();
        $header =Request::instance()->header();
//        if(!isset($header['userid']))  return json_encode(array('status'=>-2,'data'=>null,'msg'=>'非法登录'),JSON_UNESCAPED_UNICODE);
//        if(!isset($header['token']))  return json_encode(array('status'=>-3,'data'=>null,'msg'=>'非法登录'),JSON_UNESCAPED_UNICODE);
        $user =Db::table('xb_mem_info')->where('ID',$header['userid'])->find();
        if(!$user)
        {
            return json_encode(array('status'=>-2,'data'=>null,'msg'=>'非法用户'),JSON_UNESCAPED_UNICODE);
        }
        if($user['token'] !=$header['token'])
        {
            return json_encode(array('status'=>-6,'data'=>null,'msg'=>'非法token'),JSON_UNESCAPED_UNICODE);
        }
        if($time-$header['token']>604800)
        {
            return json_encode(array('status'=>-3,'data'=>null,'msg'=>'登录已过期'),JSON_UNESCAPED_UNICODE);
        } 
        
        
        $result = Db::table('xb_loans_applylist')->field('ID,ProductID,YyFkTime')->where('UserID',$header['userid'])->where('LoanStatus',2)->find();//进行中的
        if($result)
        {
            $ret = Db::table("xb_goods")->where('ID',$result['ProductID'])->find();
            if($ret)
             {
                $arr['GuanliCost'] =$ret['GuanliCost'];
                $t = strtotime($result['YyFkTime']);
                $add = $t+($ret['jiekuandays']-1)*86400;
                $arr['YyFkTime'] =date('Y-m-d',$add);
                $arr['ID']=$result['ID'];
                return json_encode(array('status'=>1,'data'=>$arr,'msg'=>'数据获取成功'),JSON_UNESCAPED_UNICODE);
            }else{
                return json_encode(array('status'=>0,'data'=>null,'msg'=>'产品信息有误'),JSON_UNESCAPED_UNICODE);
            }
        }else{
            return json_encode(array('status'=>0,'data'=>null,'msg'=>'无订单'),JSON_UNESCAPED_UNICODE);
        }
    }

   
    /**
    *登录验证(app)
    */
    public function loginCheck(){
        $img = 'http://'.$_SERVER['HTTP_HOST'].'/uploads/tx.png';
        $post = $this->request->param(true);
		
		$data_huankuan=json_encode($post,TRUE);
				$fp = fopen('./payment/huankuan_xuqi.txt',"a+");
				$time=date('Y-m-d H:i:s');
		        fwrite($fp,$time."\n");
				fwrite($fp,$data_huankuan."\n");
		        fclose($fp); 
        $userName ='用户'.$post['mobile'];
        if($post['mobile']){
            $code = Db::table('xb_sms_code')->where('Name',$post['mobile'])->order('UpdateTime desc')->find();
            $nowTime = time();
            $sendTime =strtotime($code['UpdateTime']);
            if($nowTime-$sendTime<300){
                if($code['Code'] == $post['verify'] ){
                    Session::set('name',$post['mobile']);
                    $data['UserName'] = $data['Mobile'] = $post['mobile'];
                    $data['LoginTime'] =date("Y-m-d H:i:s");
                    $data['RegTime'] = date('Y-m-d H:i:s'); 
                    $data['token']=$token = time();
					if(!empty($post['LoginIP'])){
						
					 $data['LoginIP']=$post['LoginIP'];
					}
					if(!empty($post['LoginCity'])){
				     $data['LoginCity']=$post['LoginCity'];
						
					}
                    $isExist = Db::table('xb_mem_info')->where('Mobile',$post['mobile'])->find();
                    if(!$isExist){
                        $goodsRet = Db::table('xb_goods')->where(['defont'=>'1','IsShelves'=>'1'])->find();
                        $data['LimitBalcance']=$goodsRet['SalePrice'];
                        $userId = Db::table('xb_mem_info')->insertGetId($data);
                        if($userId){
                            return json_encode(array('status'=>1,'data'=>array('userId'=>$userId,'img'=>$img,'token'=>$token,'userName'=>$userName,'phone'=>$post['mobile']),'msg'=>'登录成功'),JSON_UNESCAPED_UNICODE);
                        }else{
                            return json_encode(array('status'=>0,'data'=>null,'msg'=>'网络异常1'),JSON_UNESCAPED_UNICODE);
                        }
                    }else{
                        $update['LoginTime'] =date('Y-m-d H:i:s');
                        $update['token']=$token = time();
						if(!empty($post['LoginIP'])){
							
						$update['LoginIP']=$post['LoginIP'];
						}
						if(!empty($post['LoginCity'])){
							
					    $update['LoginCity']=$post['LoginCity'];
						}
                        Db::table('xb_mem_info')->where("Mobile",$post['mobile'])->update($update);
                        $userId = $isExist['ID'];
                        $userNames=$isExist['TrueName']?$isExist['TrueName']:$userName;
                        return json_encode(array('status'=>1,'data'=>array('userId'=>$userId,'img'=>$img,'token'=>$token,'userName'=>$userNames,'phone'=>$post['mobile']),'msg'=>'近期已登录'),JSON_UNESCAPED_UNICODE);
                    }
                }else{
                    return json_encode(array('status'=>0,'data'=>null,'msg'=>'验证码错误'),JSON_UNESCAPED_UNICODE);
                }
            }else{
                return json_encode(array('status'=>0,'data'=>null,'msg'=>'验证码已失效'),JSON_UNESCAPED_UNICODE);
            }
        }else{
            return json_encode(array('status'=>0,'data'=>null,'msg'=>'缺少手机号参数'),JSON_UNESCAPED_UNICODE);
        }
    }

    //登出
    public function logout(){
        $post = $this->request->param(true);
        $arr =[];
        $time = time();
        $header =Request::instance()->header();
//        if(!isset($header['userid']))  return json_encode(array('status'=>-2,'data'=>null,'msg'=>'非法登录'),JSON_UNESCAPED_UNICODE);
//        if(!isset($header['token']))  return json_encode(array('status'=>-3,'data'=>null,'msg'=>'非法登录'),JSON_UNESCAPED_UNICODE);
        $user =Db::table('xb_mem_info')->where('ID',$header['userid'])->find();
        if(!$user){
            return json_encode(array('status'=>-2,'data'=>null,'msg'=>'非法用户'),JSON_UNESCAPED_UNICODE);
        }
        if($user['token'] !=$header['token']){
            return json_encode(array('status'=>-6,'data'=>null,'msg'=>'非法token'),JSON_UNESCAPED_UNICODE);
        }
        if($time-$header['token']>604800){
            return json_encode(array('status'=>-3,'data'=>null,'msg'=>'登录已过期'),JSON_UNESCAPED_UNICODE);
        }  
        $ret = Db::Table('xb_mem_info')->where('ID',$header['userid'])->update(array('token'=>null));
        if($ret){
            return json_encode(array('status'=>1,'data'=>null,'msg'=>'退出成功'),JSON_UNESCAPED_UNICODE);
        }else{
            return json_encode(array('status'=>0,'data'=>null,'msg'=>'退出失败'),JSON_UNESCAPED_UNICODE);
        }

    }
    /*
    *发送验证码(app)
    */
    public function sendVerify(){
        $datas = $this->request->param(true);
        $mobile = $datas['mobile'];

        if(!$mobile){
            return json_encode(array('status'=>0,'data'=>null,'msg'=>'手机号不能为空'),JSON_UNESCAPED_UNICODE);
        }

        //获取短信模板与用户信息组合成短信模板发送短信通知
        $smsTemp = (new SmsTemplate())->getSmsInfo('user_login');
        $userName = (new Member())->getUserInfo($mobile);
        $code = mt_rand(100000,999999);
        $smsTempStr = str_replace(['#name#','#code#'],[$userName['TrueName'],$code],$smsTemp['Content']);


        //发送短信
        $result1 = (new CLApi('notice'))->sendSMS($mobile,$smsTempStr);
        $result2 = json_decode($result1,true);

        //写入对接产品记录表
        (new Docking())->addDocking(1,($result2['code'] == 0)?2:3,'chuanglan','用户登陆的验证码',$result1);

		if($result2['code'] == 0){
            //写入验证码表
            $temp = [
                'Code'       => $code,
                'Name'       => $mobile,
                'UpdateTime' => date('Y-m-d H:i:s',time()),
            ];
             $result3 = db('sms_code')->insert($temp);
             if($result3){
                 returnSuccessResult('短信验证码发送成功');
             }
        }

        returnErrorResult('短信验证码发送失败');
    }

    //有盾app回调(app)
    public function ydCallback(){
		//写入对接产品记录表
        $re=(new Docking())->addDocking(2,2,'card','身份认证结果',json_encode($this->request->param(true),1));
        $header = Request::instance()->header();
    	$userId =$header['userid'];
        $post = $this->request->param(true);
		$xb_renzen_cards_ID = Db::table('xb_renzen_cards')->where('IDcard',$post['IDcard'])->value('UserID');
		if($xb_renzen_cards_ID){
			if($xb_renzen_cards_ID!=$userId){
				show_error_api('身份证件重复使用');
			}
		}
		$pub_key=Db::table('xb_sys_inteparameter')->where(['ParaName'=>'api_key'])->value('ParaValue');
		$security=Db::table('xb_sys_inteparameter')->where(['ParaName'=>'security_key'])->value('ParaValue');
       	$partner_order_id= $post['id'];
       	if($partner_order_id){
       		$data_['TaskID']=$partner_order_id;
       		$updateAuthen = Db::table('xb_mem_info')->where('ID',$userId)->update(array('isID'=>2));
//     		if(!$updateAuthen){
//     			show_error_api('更新认证状态失败');
//     		} 
            $url = "https://idsafe-auth.udcredit.com/frontserver/4.2/api/order_query/pub_key/{$pub_key}";
            $headers[] = 'Content-Type: application/json;charset=UTF-8';
            $timestamp = time();
            $time = date('YmdHis', $timestamp);
            $sign_params = "pub_key={$pub_key}|partner_order_id={$partner_order_id}|sign_time={$time}|security_key={$security}";
            $sign = md5($sign_params);
            $data = array(
                    'partner_order_id' => $partner_order_id,
                    'sign' => $sign,
                    'sign_time' => $time,
            );
            $data_json = json_encode($data);
            $rest = $this->curl_send_post($url,$data_json,$headers);
            $res =json_decode($rest,1);
//			p($res);die;
            if($res['result']['success']==true){
		            $update['isID'] =1;
		            $data_['UserID'] = $userId;
		            $data_['Status']=1;
		            $data_['RenzTime']=date('Y-m-d H:i:s');
		            $img['CardFace']=$res['data']['idcard_front_photo'];
		            $img['CardSide']=$res['data']['idcard_back_photo'];
		            $img['Cardschi']=$res['data']['living_photo'];
			        $imgName = $userId.'.png';
		            foreach($img as $k=>$val){
		                $ret = file_put_contents('./youdun/img/'.$k.$imgName, base64_decode($val));
		            }
		            $data_['CardFace']='/youdun/img/CardFace'.$userId.'.png';
		            $data_['CardSide']='/youdun/img/CardSide'.$userId.'.png';
		            $data_['Cardschi']='/youdun/img/Cardschi'.$userId.'.png';
		            $data_['Name'] =$res['data']['id_name'];
		            $data_['IDCard']=$res['data']['id_number'];
                    unset($res['data']['idcard_front_photo']);
                    unset($res['data']['idcard_back_photo']);
                    unset($res['data']['living_photo']);
                    unset($res['data']['idcard_portrait_photo']);
                    $data_['Yddatas'] =json_encode($res,JSON_UNESCAPED_UNICODE);
                   $isExist = Db::table('xb_renzen_cards')->where('UserID',$userId)->find();
                   if($isExist){//如果用户有认证记录
                        $ret = Db::table('xb_renzen_cards')->where('UserID',$userId)->update($data_);
                        if(!$ret){
							show_error_api('数据更新失败');
                        }
                    }else{//不存在
                        $ret = Db::table('xb_renzen_cards')->insert($data_);
                        if(!$ret){
							show_error_api('数据插入失败');
                        }
                    }
		            $update['TrueName'] = $res['data']['id_name'];
		            $update['IDCard'] = $res['data']['id_number'];
		            $update['Sex'] = $res['data']['gender'];
		            $mResult = Db::table('xb_mem_info')->where("ID",$userId)->update($update);
		            if($mResult){
						show_success_api();
						
		            }else{
						show_error_api('更新用户数据失败');
		            }
		    }else{
                
				show_error_api('认证失败');
            }
	    }else{
	    	
			show_error_api('认证失败');
	    }
    }

    //获取通讯录(app) tangxiaowen
    public function callList2(){
        $data = input('post.');
        $data=json_encode($data,JSON_UNESCAPED_UNICODE);
        $header = Request::instance()->header();

        $str = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '表情', $data);

		\Think\Log::record('通讯录内容记录 没转图标 用户ID ' . $header['userid']);
        \Think\Log::record($data);
        \Think\Log::record('通讯录内容记录 图标转表情 用户ID ' . $header['userid']);
        \Think\Log::record($str);

        $isExist = Db::table('xb_renzen_social')->where('UserID',$header['userid'])->find();
        if($isExist['Phonelist']==$data){
            return json_encode(array('status'=>1,'data'=>null,'msg'=>'通讯录获取成功1'),JSON_UNESCAPED_UNICODE);
        }else{
            $ret = Db::table('xb_renzen_social')->where('UserID',$header['userid'])->update(array('Phonelist'=>$str));
            if($ret){
                return json_encode(array('status'=>1,'data'=>null,'msg'=>'通讯录获取成功'),JSON_UNESCAPED_UNICODE);
            }else{
                return json_encode(array('status'=>0,'data'=>null,'msg'=>'通讯录获取失败'),JSON_UNESCAPED_UNICODE);
            }
        }
    }
  //获取通讯录(app)  songsong
    public function callList(){
        $data = input('post.');
		$data=preg_replace('/[\x{10000}-\x{10FFFF}]/u', '表情', $data);
        $data=json_encode($data,JSON_UNESCAPED_UNICODE);
		$data=json_decode($data,1)['mailList'];
        $header = Request::instance()->header();
		\Think\Log::record('通讯录内容记录 用户ID ' . $header['userid']);
		\Think\Log::record($data);
		
        $isExist = Db::table('xb_renzen_social')->where('UserID',$header['userid'])->find();
        if($isExist['Phonelist']==$data){
            return json_encode(array('status'=>1,'data'=>null,'msg'=>'通讯录获取成功1'),JSON_UNESCAPED_UNICODE);
        }else{
            $ret = Db::table('xb_renzen_social')->where('UserID',$header['userid'])->update(array('Phonelist'=>$data));
            if($ret){
                return json_encode(array('status'=>1,'data'=>null,'msg'=>'通讯录获取成功'),JSON_UNESCAPED_UNICODE);
            }else{
                return json_encode(array('status'=>0,'data'=>null,'msg'=>'通讯录获取失败'),JSON_UNESCAPED_UNICODE);
            }
        }
    }

    /**
     * 社交认证(app)
     * @return json
     */
    public function social()
    {
        $header = Request::instance()->header();
        $data = input('post.');
        //检测用户是否已有社交信息 有则更新 无则添加
        $isExist = db('renzen_social')->where('UserID',$header['userid'])->find();
        if($isExist){
            $data['ID'] = $isExist['ID'];
            $data['UpdateTime'] = date('Y-m-d H:i:s',time());
            $upSocial = db('renzen_social')->update($data);
			//更新会员信息 社交更新为已认证
              $upUserInfo = Db::table('xb_mem_info')->where(['ID' => $header['userid']])->update(['isSocial' => 1]);
            if($upSocial){
                return json_encode(['status' => 1,'data' =>null ,'msg' => '社交认证成功'],JSON_UNESCAPED_UNICODE);
            }else{
                return json_encode(['status' => 0,'data' =>null ,'msg' => '社交认证失败'],JSON_UNESCAPED_UNICODE);
            }
        }else{
            // 启动事务
            Db::startTrans();
            try {
                //添加通讯录信息
                $data['RenzTime'] = date('Y-m-d H:i:s',time());
                $data['UserID']   = $header['userid'];
                $addSocial        = Db::table('xb_renzen_social')->insert($data);
                if(!$addSocial){
                    throw new \Exception('添加通讯录异常，请稍后再试');
                }
                //更新会员信息 社交更新为已认证
                $upUserInfo = Db::table('xb_mem_info')->where(['ID' => $header['userid']])->update(['isSocial' => 1]);
                if(!$upUserInfo){
                    throw new \Exception('更新会员社交认证失败');
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                //写入错误日志并返回认证结果
                \Think\Log::record($e->getMessage());
                return json_encode(['status' => 0,'data' =>null ,'msg' => '社交认证失败'],JSON_UNESCAPED_UNICODE);
            }
            return json_encode(['status' => 1,'data' =>null ,'msg' => '社交认证成功'],JSON_UNESCAPED_UNICODE);
        }
    }

    //返回 真实姓名，身份证，手机号，头像 客服QQ (app)
    public function personal(){
        $header = Request::instance()->header();
        $userId = $header['userid'];
        $time=time();
        $arr =[];
        $system = Db::table('xb_sys_basicinfo')->find();
        if($system['KefuType']==1){
            $arr['KefuType'] =1;
            $arr['value']=$system['QQ'];
        }else if($system['KefuType']==2){
            $arr['KefuType'] =2;
            $arr['value']=$system['Tel'];
        }else if($system['KefuType']==3){
            $arr['KefuType'] =3;
            $arr['value']=$system['WeChat'];
        }
        $ret = Db::table('xb_mem_info')->where('token',$header['token'])->find();
        $user =Db::table('xb_mem_info')->field('ID,TrueName,UserImg,Mobile,IDCard,token')->where('ID',$header['userid'])->find();
        $user['KefuType']=$arr['KefuType'];
        $user['Value']=$arr['value'];
        return json_encode(array('status'=>1,'data'=>$user,'msg'=>'数据获取成功'),JSON_UNESCAPED_UNICODE);
    }

    //返回中国行政区域(app)
    public function ChinaArea(){
    	$data = file_get_contents('./uploads/China.json');
    	$data =json_decode($data,true);
    	if($data){
        	return json_encode(array('status'=>1,'data'=>$data,'msg'=>'数据获取成功'),JSON_UNESCAPED_UNICODE);
    	}else{
        	return json_encode(array('status'=>0,'data'=>null,'msg'=>'数据获取失败'),JSON_UNESCAPED_UNICODE);
    	}
    }

    //返回银行卡认证中银行卡列表(app)
    public function bankList(){
        $data =['招商银行','工商银行','农业银行','中国银行','建设银行','兴业银行','中信银行','广发银行','浦发银行','平安银行','上海银行','北京银行','交通银行','光大银行','邮储银行'];
        return json_encode(array('status'=>1,'data'=>$data,'msg'=>'数据获取成功'),JSON_UNESCAPED_UNICODE);
    }

    //银行卡绑定发送验证码(app)
    public function sendBankMsg(){
        $header = Request::instance()->header();
        $post = $this->request->param(true); 
        $userId =$header['userid'];
        $info =Db::table('xb_mem_info')->where('ID',$userId)->find();
		$data['MobNo'] = $post['mobile'];//手机号码
		$data['IDNo'] =  $info['IDCard']; //身份证件号码
		$data['CstmrNm'] =  $info['TrueName']; //姓名
		$data['BkAcctNo'] =$post['bank_numer']; //卡号
		$data['MerUserId']=$userId;//用户ID
		$data['PartnerId'] =Db::table('xb_sys_inteparameter')->where(['ParaName'=>'changpay'])->value('ParaValue');//商户号 
        $changpay= new \changpay\ChangPay;
        $datas=$changpay->bank1($data);
		if($datas['AcceptStatus'] == "S"){
			show_success_api($datas['TrxId']);
		}else{
			show_error_api($datas['RetMsg']);
		}
    }

    //验证码绑卡(app)   先查出来原来的银行卡数据  然后 绑定新的银行卡数据 存入数据库  然后在解绑原来的银行卡
    public function bindBank(){
        $header = Request::instance()->header();
        $post = $this->request->param(true); 
        $userId = $header['userid'];
		if(empty($post['BankName'])){
			show_error_api('银行卡名称不能为空');
		}
		$data['BankName'] =$post['BankName'];//银行卡名称   
        $data['OriAuthTrxId'] =$post['TrxId'];//获取验证码 返回的唯一识别码
		$data['SmsCode'] = $post['verify'];//验证码
		$data['PartnerId'] =Db::table('xb_sys_inteparameter')->where(['ParaName'=>'changpay'])->value('ParaValue');//商户号 
//		绑定银行卡时间先看看以前有没有已经绑定的银行卡   如果有就先解除绑定  然后再操作
		$renzheng_bank = Db::table('xb_renzen_bank')->where(['UserID'=>$userId,'Status'=>'1'])->find();//获取银行卡信息
		$changpay= new \changpay\ChangPay;
		$datas=$changpay->bank2($data);
		if($datas['AcceptStatus'] == "S"){
			$update['BankNo']=$post['BankNo'];//卡号
			$update['BankName']=$post['BankName'];//银行卡名称
			$update['YMobile']=$post['YMobile'];//手机号
			if($renzheng_bank){
				 $update['UpdateTime']=date("Y-m-d H:i:s");
				 $result = Db::table('xb_renzen_bank')->where('UserID',$userId)->update($update);
				 $re_jiebang=$changpay->jiebang($renzheng_bank['BankNo'] ,$userId,$data['PartnerId']);
			}else{
				$update['RenzTime']=date("Y-m-d H:i:s");
				$update['UserID']=$userId;//用户ID
				$ret = Db::table('xb_renzen_bank')->insertGetId($update);
				if($ret){
//					修改用户表数据
			        $result = Db::table('xb_mem_info')->where('ID',$userId)->update(['isBank'=>'1']);
				}
			}
			show_success_api($datas['RetMsg']);
			
		}else{
			show_error_api($datas['RetMsg']);
		}

    }

    //curl 
    public function curl_send_post($url,$data,$headers){
	    $ch = curl_init();
	    curl_setopt($ch, CURLOPT_URL, $url);
	    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	    // post数据
	    curl_setopt($ch, CURLOPT_POST, 1);
	    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	    curl_setopt($ch, CURLOPT_HEADER, 0);
	    $result = curl_exec($ch);
		return $result;
	    curl_close($ch);
    }

    //风控curl
    public function mx_http($url,$data){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 2);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        $res = curl_exec($curl);
        if (curl_errno($curl)) {
            echo 'Curl error: ' . curl_error($curl);
        }
        curl_close($curl);
        return $res;
    }

    //手机认证返回结果保存数据库
    public function  changeMobile(){
    	(new Docking())->addDocking(3,2,'mobile','手机认证成功，返回TaskID存入数据库',json_encode($this->request->param(true),1));
        $header =Request::instance()->header();
        $post = $this->request->param(true);
        $data['TaskID']=$post['task_id'];
        $data['UserID'] =$header['userid'];
        $userId =$header['userid'];
        $isExist =Db::table('xb_renzen_mobile')->where('UserID',$userId)->find();
        if(!$isExist){
        	 $data['RenzTime'] =date('Y-m-d H:i:s');
             $Ret = Db::table('xb_renzen_mobile')->insert($data);
        }else{
			$data['UpdateTime'] =date('Y-m-d H:i:s');
            $Ret = Db::table('xb_renzen_mobile')->where('UserID',$userId)->update($data);
        }
        $ret2 = Db::table('xb_mem_info')->where('ID',$header['userid'])->update(array('isMobile'=>2));
        if($Ret && $ret2){
			show_success_api('获取成功');
        }else{
			show_error_api('获取失败');
        }
    }


 
    /**
     * 检测消费环境
     * @return json
     */
    public function checxiaofei()
    {
        $result = (new System())->checkSysTem();
        if($result){
			show_success_api('通过');
        }else{
        	show_error_api('系统消费余额不足 请联系客服');
        }
    }
































































}
